package com.heima.user.service.impl;

import com.heima.common.constants.user.UserRelationConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.service.ApUserRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class ApUserRelationServiceImpl implements ApUserRelationService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public ResponseResult follow(UserRelationDto dto) {
        //判断数据是否合法（在实体类中已经判断）
        //获取当前登录的用户id
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null || user.getId() == null) {
            CustomException.cust(AppHttpCodeEnum.NEED_LOGIN, "请先登录！");
        }
        Integer userId = user.getId();
        Integer authorApUserId = dto.getAuthorApUserId();
        Short operation = dto.getOperation();
        //判断当前用户有没有关注目标作者
        Double score = redisTemplate.opsForZSet().score(UserRelationConstants.FOLLOW_LIST + userId, String.valueOf(authorApUserId));
        if (score != null && operation == 0) {
            CustomException.cust(AppHttpCodeEnum.DATA_EXIST, "你已经关注过该作者");
        }
        //不能自己关注自己
        if (userId == authorApUserId) {
            CustomException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "不能自己关注自己");
        }
        //开启redis事务
        redisTemplate.multi();
        try {
            //判断是关注还是取消关注
            if (operation == 0) {
                //执行关注操作
                redisTemplate.opsForZSet().add(UserRelationConstants.FOLLOW_LIST + userId, String.valueOf(authorApUserId), System.currentTimeMillis());
                redisTemplate.opsForZSet().add(UserRelationConstants.FANS_LIST + authorApUserId, String.valueOf(userId), System.currentTimeMillis());
            } else {
                //执行取关操作
                redisTemplate.opsForZSet().remove(UserRelationConstants.FOLLOW_LIST + userId, String.valueOf(authorApUserId));
                redisTemplate.opsForZSet().remove(UserRelationConstants.FANS_LIST + authorApUserId, String.valueOf(userId));
            }
            //提交事务
            redisTemplate.exec();
            return ResponseResult.okResult();
        } catch (Exception e) {
            e.printStackTrace();
            //事务回滚
            redisTemplate.discard();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "关注/取关失败");
        }
    }
}